package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class ContextUtils {
	 
	private static final String PRODUCTION_PROFILE = "prod";
    private static final String STAGE_PROFILE = "stage";
	private static Logger log = LoggerFactory.getLogger(ContextUtils.class);
    public static ApplicationContext context;

    private ContextUtils() {
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
    
    /**
     * 判断当前环境是否是线上环境：prod或stage
     * @return
     */
    public static boolean isProfileActived() {
        String[] profiles = ContextUtils.context.getEnvironment().getActiveProfiles();
        if (profiles == null || profiles.length == 0) {
            return false;
        }
        for (String val : profiles) {
        	log.debug("current profile from context is: {}", val);
            if (val.equalsIgnoreCase(PRODUCTION_PROFILE) || val.equalsIgnoreCase(STAGE_PROFILE)) {
                return true;
            }
        }
        return false;
    }
}